package com.fenda.gallery

import android.annotation.SuppressLint
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import androidx.navigation.findNavController
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter

import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import io.supercharge.shimmerlayout.ShimmerLayout


class GalleryAdapter(val call:GetData) : ListAdapter<PhotoItem, MyViewHolder>(DIFFCALLBACK) {

    interface GetData{
        fun callBack()
    }

    //创建一个属于类的常量，类似于JAVA的静态域，伴生对象
    companion object {
        const val NORMAL_VIEW_TYPE = 0
        const val FOOTER_VIEW_TYPE = 1
    }

    var footerViewStatus = DATA_STATUS_CAN_LOAD_MORE

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val myViewHolder: MyViewHolder
        if (viewType == NORMAL_VIEW_TYPE) {
            val inflate =
                LayoutInflater.from(parent.context).inflate(R.layout.gallery_cell, parent, false)
            myViewHolder = MyViewHolder(inflate)
            myViewHolder.itemView.setOnClickListener {
                Bundle().apply {
//                putParcelable("PHOTO",getItem(myViewHolder.adapterPosition))
//                myViewHolder.itemView.findNavController().navigate(R.id.action_galleryFragment_to_photoFragment,this)
                    putParcelableArrayList("PHOTO", ArrayList(currentList))
                    putInt("PHOTO_POSITION", myViewHolder.adapterPosition)
                    myViewHolder.itemView.findNavController()
                        .navigate(R.id.action_galleryFragment_to_photoPagerFragment, this)
                }
            }
        } else {
            val inflate =
                LayoutInflater.from(parent.context).inflate(R.layout.gallery_footer, parent, false)
                    .also {
                        (it.layoutParams as StaggeredGridLayoutManager.LayoutParams).isFullSpan =
                            true
                        val progressBar = it.findViewById<ProgressBar>(R.id.progressBar)
                        val textView = it.findViewById<TextView>(R.id.textView)
                        it.setOnClickListener {
                            progressBar.visibility = View.VISIBLE
                            textView.text = "正在加载"
                            call.callBack()
                        }
                    }
            myViewHolder = MyViewHolder(inflate)
        }

        return myViewHolder
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        if (position == itemCount - 1) {
            //最后一个
            with(holder) {
                when (footerViewStatus) {
                    DATA_STATUS_CAN_LOAD_MORE -> {
                        progressBar?.visibility = View.VISIBLE
                        textView?.text = "正在加载"
                        itemView.isClickable = false
                    }
                    DATA_STATUS_NO_MORE -> {
                        progressBar?.visibility = View.GONE
                        textView?.text = "全部加载完毕"
                        itemView.isClickable = false
                    }
                    DATA_STATUS_NETWORK_ERROR -> {
                        progressBar?.visibility = View.GONE
                        textView?.text = "网络故障，点击重试"
                        itemView.isClickable = true
                    }
                }
            }
            return
        }
        //先启动shimmer
        holder.shimmerLayoutGallery?.apply {
            setShimmerColor(0x55FFFFFF)
            setShimmerAngle(0)
            startShimmerAnimation()
        }
        //设置固定高度，防止Grid重新排序
        holder.image?.layoutParams?.height = getItem(position).photoHeight
        holder.image?.let {
            Glide.with(holder.itemView)
                .load(getItem(position).preViewUrl)
                .placeholder(R.drawable.photo_placeholfer)
                .listener(object : RequestListener<Drawable> {
                    override fun onLoadFailed(
                        e: GlideException?,
                        model: Any?,
                        target: Target<Drawable>?,
                        isFirstResource: Boolean
                    ): Boolean {
                        return false
                    }

                    override fun onResourceReady(
                        resource: Drawable?,
                        model: Any?,
                        target: Target<Drawable>?,
                        dataSource: DataSource?,
                        isFirstResource: Boolean
                    ): Boolean {
                        return false.also { holder.shimmerLayoutGallery?.stopShimmerAnimation() }
                    }

                })
                .into(it)
        }
    }

    //比较器
    object DIFFCALLBACK : DiffUtil.ItemCallback<PhotoItem>() {
        override fun areItemsTheSame(oldItem: PhotoItem, newItem: PhotoItem): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: PhotoItem, newItem: PhotoItem): Boolean {
            return oldItem == newItem
        }

    }

    //增加一个试图上的位置及给footerView一个位置
    override fun getItemCount(): Int {
        return super.getItemCount() + 1
    }

    override fun getItemViewType(position: Int): Int {
        //position是从0开始的
        return if (position == itemCount - 1) FOOTER_VIEW_TYPE else NORMAL_VIEW_TYPE
    }
}


class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    var shimmerLayoutGallery: ShimmerLayout? = null
    var image: ImageView? = null
    var progressBar: ProgressBar? = null
    var textView: TextView? = null

    init {
        shimmerLayoutGallery = itemView.findViewById(R.id.shimmerLayoutGallery)
        image = itemView.findViewById(R.id.imageView)
        progressBar = itemView.findViewById(R.id.progressBar)
        textView = itemView.findViewById(R.id.textView)
    }

}

